const api = require("../utils/api.js");
const util = require("../utils/utils.js");
const session = require("../utils/session.js");
const Storage = require("./storage.js");
const config = require("./config.js");
const toast = require("./toasts.js");

var app = getApp();

exports.getLocation = function(that, success) {
  wx.getLocation({
    success: function(res) {
      // console.log(res)
      that.setData({
        hasLocation: true,
        location: {
          lng: res.longitude,
          lat: res.latitude
        }
      })
      if (success) {
        success();
      }
    }
  })
}

exports.getAddress = function(that) {
  if (that.data.address) {
    return;
  }

  request("/user/getAddress", {
      lat: that.data.location.lat,
      lng: that.data.location.lng
    })
    .then((data) => {
      // console.log(data);
      that.setData({
        address: data.result
      });
    })
}


exports.shareToGroup = function(params, encryptedData, sessionKey, iv) {
  request("/share/toGroup", {
      param: params,
      encryptedData: encryptedData,
      sessionKey: sessionKey,
      iv: iv
    })
    .then((data) => {

    })
}

exports.onShareAppMessage = function(that, res, title, path) {
  if (res.from === 'button') {
    // 来自页面内转发按钮
    // console.log(res.target)
  }

  var curr = this;
  var ownerId = null;
  if (that.data.user) {
    ownerId = that.data.user.id;
  }
  var param = path.substring(path.indexOf("?") + 1);
  var path = path + "&mode=share&ownerId=" + ownerId;

  return {
    title: title,
    path: path,
    success: function(res) {
      util.showToast("分享成功");
      // console.log("====shareTickets===" + res.shareTickets);
      // 如果存在是转发群聊
      if (res.shareTickets) {
        wx.getShareInfo({
          shareTicket: res.shareTickets,
          success: function(res) {
            // console.log("====errMsg===" + res.errMsg);
            // console.log("====encryptedData===" + res.encryptedData);
            // console.log("====iv===" + res.iv);
            curr.shareToGroup(param, res.encryptedData, util.getFromCache("session_key"), res.iv);
          },
          fail: function(res) {
            // console.log("分享失败" + res);
            // 转发失败
          }
        });
      }
    },
    fail: function(res) {
      console.log("分享失败" + res);
      // 转发失败
    }
  }
}

exports.getSimpleInfo = function(that) {

  request("/user/simpleInfo", {})
    .then((data) => {
      // console.log(data);
      var user = data.result;
      that.setData({
        user: user
      });
    })
}

exports.getUserInfo = function(that) {
  var user = util.getFromCache("userinfo");
  if (user) {
    var info = JSON.parse(user);
    that.setData({
      user: info
    });
  }
  request("/user/info", {})
    .then((data) => {
      // console.log(data);
      var user = data.result;
      user.d1name = util.getD(user.d1);
      user.d2name = user.d2 + "段";
      that.setData({
        user: user
      });
      util.putCache("userinfo", JSON.stringify(data.result));
    })
}

exports.clearUserInfo = function() {
  util.putCache("userinfo", null);
}

exports.getAllCats = function(that, success) {
  var allcats = util.getFromCache("allcats");
  if (allcats) {
    var allcats = JSON.parse(allcats);
    that.setData({
      allcats: allcats
    });
  }

  request("/tp/allCats", {})
    .then((data) => {
      // console.log(data);
      var allcats = data.result;
      that.setData({
        allcats: allcats
      });
      util.putCache("allcats", JSON.stringify(data.result));

      if (success) {
        success();
      }
    })
}

exports.getHotWords = function(that, catId, success) {
  var param = {};
  if (catId != null) {
    param = {
      catId: catId
    };
  }

  request("/tp/queryKeywords", param)
    .then((data) => {
      // console.log(data);
      var hotwords = data.result;
      that.setData({
        hotwords: hotwords
      });

      if (success) {
        success();
      }
    })
}

exports.getCatName = function(that, catId) {
  var allcats = util.getFromCache("allcats");
  if (allcats) {
    var allcats = JSON.parse(allcats);
    for (var i = 0; i < allcats.length; i++) {
      if (allcats[i].id == catId) {
        return allcats[i].name;
      }
    }
  }
  return '时光投票';
}

exports.getBanner = function(that, success) {
  var param = {};

  request("/banner/getAll", param)
    .then((data) => {
      // console.log(data);
      var banners = data.result;
      that.setData({
        banners: banners
      });

      if (success) {
        success();
      }
    })
}

exports.saveUserInfo = function(e, that, success) {
  if (e.detail.userInfo) {
    this.saveInfo(that, e.detail.userInfo.nickName, e.detail.userInfo.avatarUrl, e.detail.userInfo.province, e.detail.userInfo.city, e.detail.userInfo.gender, e.detail.encryptedData, session.getSessionKey(), e.detail.iv, success);
  }
}


exports.locToAddress = function(lat, lng, that, success) {
  if (!lat || !lng) {
    return;
  }

  var param = {
    lat,
    lng
  };

  api.loc_to_address(param)
    .then((data) => {
      // console.log(data);
      if (data.success) {
        var loc = data.result;
        if (that) {
          that.setData({
            loc
          })
        }

        if (success) {
          success();
        }
      } else {
        toast.show(data.errorMsg);
      }
    })
}

exports.bindPhone = function(e, that, success) {
  if (e.detail.errMsg.indexOf('fail') != -1) {
    return;
  }

  var param = {};
  var sessionKey = session.getSessionKey();
  var encryptedData = e.detail.encryptedData;
  var iv = e.detail.iv;

  if (encryptedData) {
    param.encryptedData = encryptedData;
    param.iv = iv;
    param.sessionKey = sessionKey;
  }

  api.bind_wx_phone(param)
    .then((data) => {
      // console.log(data);
      if (data.success) {
        var phone = data.result;
        var userInfo = session.getUserSync();
        if (userInfo) {
          userInfo.phone = phone;
          session.putUser(userInfo);

          that.setData({
            user: userInfo
          });
        }

        if (success) {
          success();
        }
      } else {
        toast.show(data.errorMsg);
      }
    })
}

exports.saveInfo = function(that, nickName, logo, province, city, gender, encryptedData, sessionKey, iv, success) {
  var param = {};
  if (nickName != null) {
    param.nickName = nickName;
  }
  if (logo != null) {
    param.logo = logo;
  }
  if (province != null) {
    param.province = province;
  }
  if (city != null) {
    param.city = city;
  }
  if (gender != null) {
    if (gender == 1) {
      param.sex = 'MALE';
    } else if (gender == 2) {
      param.sex = 'FEMALE';
    } else {
      param.sex = 'UNKNOWN';
    }
  } else {
    param.sex = 'UNKNOWN';
  }

  if (encryptedData) {
    param.encryptedData = encryptedData;
    param.iv = iv;
    param.sessionKey = sessionKey;
  }

  if (config.tryopenid) {
    param.unionId = config.tryopenid;
  }

  api.saveInfo(param)
    .then((data) => {
      // console.log(data);
      if (data.result.user) {
        let token = data.result.token;
        let uid = data.result.user.id;
        let user = data.result.user;
        Storage.set("auth", {
          token: token,
          uid: uid
        }, 24 * 60 * 60 * 10);
        Storage.set("current_user", user, 24 * 60 * 60 * 10);

        that.setData({
          user: user
        });
      } else {
        var userInfo = session.getUserSync();
        if (userInfo) {
          userInfo.nickName = nickName;
          userInfo.realName = nickName;
          userInfo.logo = logo;
          session.putUser(userInfo);

          that.setData({
            user: userInfo
          });
        }
      }

      if (success) {
        success();
      }
    })
}

exports.myInfo = function(that, success) {
  var param = {};

  api.myInfo(param)
    .then((data) => {
      // console.log(data);
      if (success) {
        success(data.result);
      }

      if (data.success) {
        that.setData({
          user: data.result
        });
        session.putUser(data.result);
      }
    })
}

exports.banners = function(that, success) {
  var param = {};

  api.banner_getall(param)
    .then((data) => {
      // console.log(data);
      if (success) {
        success(data.result);
      }

      if (data.success) {
        that.setData({
          banners: data.result
        });
      }
    })
}

exports.mySeller = function(that, success) {
  var param = {};

  api.seller_my(param)
    .then((data) => {
      // console.log(data);
      if (success) {
        success(data.result);
      }

      if (data.success) {
        that.setData({
          seller: data.result
        });
      }
    })
}

exports.myCard = function(that, success) {
  var param = {};

  api.card_my(param)
    .then((data) => {
      // console.log(data);
      if (success) {
        success(data.result);
      }

      if (data.success) {
        that.setData({
          user: data.result
        });
        session.putUser(data.result);
      }
    })
}

exports.sellerInfo = function(that, sellerId, salesId, success) {
  var param = {};
  if (sellerId) {
    param.sellerId = sellerId;
  }
  if (salesId) {
    param.salesId = salesId;
  }

  api.seller_getbyid(param)
    .then((data) => {
      // console.log(data);
      if (success) {
        success(data.result);
      }

      if (data.success) {
        that.setData({
          seller: data.result
        });
      }
    })
}


exports.updateUnRead = function(that) {
  var last = wx.getStorageSync("lastmsg");
  var param = {};
  if (last) {
    param.time = util.tf('yyyy-MM-dd hh:mm:ss', last);;
  }

  api.msg_unreadcount(param)
    .then((data) => {
      if (data.success) {
        if (data.result.count > 0) {
          wx.setTabBarBadge({
            index: 2,
            text: data.result.count + '',
          });
        } else {
          wx.removeTabBarBadge({
            index: 2
          });
        }

        wx.setStorageSync('lastmsg', new Date().getTime());

        if (that) {
          that.setData({
            msgCount: data.result.news
          })
        }
      }
    })
}

exports.departments = function(that, needDetail) {
  var last = wx.getStorageSync("lastmsg");
  var param = {};
  if (needDetail) {
    param.needDetail = needDetail;
  } else {
    param.needDetail = false;
  }

  api.seller_departments(param)
    .then((data) => {
      if (data.success) {
        if (that) {
          var names = [];
          var dps = data.result;
          for (var i = 0; i < dps.length; i++) {
            names.push(dps[i].name);
          }
          that.setData({
            departments: dps,
            dpNames: names
          })
        }
      }
    })
}


exports.laterRefresh = function(that, refresh) {
  var usr = session.getUserSync();

  if (!usr) {
    setTimeout(function() {
      refresh();
    }, 3000) //延迟时间
  } else {
    refresh();
  }
}

exports.laterRun = function(that, t,fun) {
  
  setTimeout(function() {
    fun();
  }, t?t:3000) //延迟时间
}

exports.saveFormId = function(e) {
  if (!e) {
    return;
  }

  var formId = e.detail.formId;
  if (!formId) {
    return;
  }

  var param = {
    formId: formId
  };

  api.op_formid(param)
    .then((data) => {})
}